<template>
	<e-list-item v-for="item in historyChatMsgList" :key="item.mid">
		<msgItem :info="item" :primary="primary" :unitEn="unitEn" :user="IMUserId"  />
	</e-list-item>
</template>

<script lang="ts">
	export default {
		// #ifdef MP-WEIXIN
		// 将自定义节点设置成虚拟的，更加接近Vue组件的表现，能更好的使用e-flex属性
		options: {
			virtualHost: true
		}
		// #endif
	}
</script>
<script lang="ts" setup>
	import { ref, onUnmounted } from 'vue'
	import msgItem from './msgItem.vue'
	import {
		getIMUserId
	} from '@/common/utils/IM'
	import type {
		ReceiveMsg
	} from '@/common/utils/IM'

	// #ifndef APP-NVUE
	import vueIM from '@/common/utils/IM/IM'
	// #endif

	const props = defineProps({
		primary: String,
		unitEn: String,
		user: String,
		bId: String,
	})
	
	const emit = defineEmits(['toView'])

	let IM : typeof vueIM

	// #ifdef APP-NVUE
	IM = getApp().globalData.IM
	// #endif
	// #ifndef APP-NVUE
	IM = vueIM
	// #endif
	
	const IMUserId = getIMUserId()
	const historyChatMsgList = ref<ReceiveMsg[]>([])

	const mySessionKey = `${IMUserId}-${props.bId}`
	
	uni.$emit('sessionOper',mySessionKey)

	const dispMsg = ({ curChatMsg, sessionKey } : { curChatMsg : ReceiveMsg, sessionKey : string }) => {
		if (sessionKey === mySessionKey) {
			// 是发送或接收到当前聊天对象的消息
			historyChatMsgList.value.push(curChatMsg)
			emit('toView')
		}
	}

	const init = () => {
		const msg = new IM.message('WxFriendMsgReq', {
			body: {
				chatlinkid: props.user,
				startmid: ''
			}
		})
		IM.send(msg)

	}

	init()

	// 添加监听
	uni.$on('newChatMsg', dispMsg)
	uni.$on('initChatMsg', (data:ReceiveMsg[]) => {
		historyChatMsgList.value = data
		emit('toView')
	})

	onUnmounted(() => {
		// 解除监听
		uni.$off('newChatMsg', dispMsg)
		uni.$off('initChatMsg')
		uni.$emit('sessionOper','')
	})
</script>

<style>
</style>